﻿namespace TodoList
{
    #region using

    using System;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Model;
    using Service;
    using StructureMap;

    #endregion

    public partial class _Default : Page
    {
        #region Constants and Fields

        private readonly ITodoService _service;

        #endregion

        #region Constructors and Destructors

        public _Default()
        {
            _service = ObjectFactory.GetInstance<ITodoService>();
        }

        #endregion

        #region Methods

        protected void GridCancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            TodoGrid.EditIndex = -1;
            BindGrid();
        }

        protected void GridDelete(object sender, GridViewDeleteEventArgs e)
        {
            var id = int.Parse(TodoGrid.DataKeys[e.RowIndex].Value.ToString());
            _service.Delete(id);
            BindGrid();
        }

        protected void GridEdit(object sender, GridViewEditEventArgs e)
        {
            TodoGrid.EditIndex = e.NewEditIndex;
            BindGrid();
        }

        protected void GridInsert(object sender, EventArgs e)
        {
            var todo = new Todo { Title = txtNewTodo.Text };
            _service.Insert(todo);
            txtNewTodo.Text = string.Empty;
            BindGrid();
        }

        protected void GridUpdate(object sender, GridViewUpdateEventArgs e)
        {
            var row = TodoGrid.Rows[e.RowIndex];
            var id = int.Parse(TodoGrid.DataKeys[e.RowIndex].Value.ToString());
            var title = e.NewValues["Title"].ToString();
            var done = e.NewValues["Done"].ToString();

            var update = new Todo { Id = id, Title = title, Done = bool.Parse(done) };

            _service.Update(update);
            TodoGrid.EditIndex = -1;
            BindGrid();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack) BindGrid();
        }

        private void BindGrid()
        {
            TodoGrid.DataSource = _service.All().ToList();
            TodoGrid.DataBind();
        }

        #endregion
    }
}